package com.education.springbootdemo.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import  com.education.springbootdemo.vo.Token;

import java.io.Serializable;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenUtils {

    private static final String secret = "123456";

    //创建token
    public static Token CreateToken(Serializable userid, HashMap<String,Object> other) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", userid);
        String token = JWT.create()
                .withClaim("user", map)
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60))
                .sign(Algorithm.HMAC256(secret));

        Base64.Encoder encoder = Base64.getEncoder();

        byte[] encodeStr = encoder.encode(token.getBytes());

        token = new String(encodeStr);

        return new Token(token);
    }

    public static Map<String , Claim> parseToken(String auth) {

        Base64.Decoder decoder = Base64.getDecoder();
        byte[] bts = decoder.decode(auth);
        //生成验证器
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();

        //验证token，生成解析后的JWT对象
        DecodedJWT decodedJWT = jwtVerifier.verify(new String(bts));

        //获取所有载荷
        Map<String, Claim> claims = decodedJWT.getClaims();
        return claims;
    }


}
